import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/services/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/utils/loading_util.dart';

/// 我的发布页面控制器
/// 
/// 负责：
/// - 我的发布管理（进行中、已结束、我的参与）
/// - 活动编辑、删除等操作
/// - 活动管理（查看参与者）
class MyPublishController extends GetxController {
  MyPublishController();

  // ==================== 服务依赖 ====================
  final UserService _userService = Get.find<UserService>();
  
  // ==================== 标签切换 ====================
  final publishTabIndex = 0.obs;
  
  // ==================== 我的发布 ====================
  final myOngoingActivities = <ActivityEntity>[].obs;
  final myEndedActivities = <ActivityEntity>[].obs;
  final myParticipatedActivities = <ActivityEntity>[].obs;
  final isLoadingMyActivities = false.obs;
  
  @override
  void onReady() {
    super.onReady();
    _handleRouteArguments();
    loadMyActivities();
  }
  
  /// 处理路由参数（用于从其他页面跳转并切换标签）
  void _handleRouteArguments() {
    final args = Get.arguments;
    if (args != null && args is Map<String, dynamic>) {
      // 🎯 切换到指定的子标签
      final switchToSubTab = args['switchToSubTab'] as int?;
      if (switchToSubTab != null && switchToSubTab >= 0 && switchToSubTab <= 2) {
        publishTabIndex.value = switchToSubTab;
        
        debugPrint('🎯 路由参数：切换到子标签 $switchToSubTab');
      }
    }
  }
  
  // ==================== 标签切换 ====================
  
  /// 切换发布子Tab
  void switchPublishTab(int index) {
    publishTabIndex.value = index;
  }
  
  // ==================== 我的发布 ====================
  
  /// 加载我的发布
  Future<void> loadMyActivities() async {
    if (!_userService.isLoggedIn) {
      debugPrint('⚠️ 用户未登录，无法加载我的发布');
      return;
    }
    
    if (isLoadingMyActivities.value) return;
    
    isLoadingMyActivities.value = true;
    
    try {
      final userId = _userService.currentUserProfile?.userid;
      if (userId == null) {
        debugPrint('❌ 用户ID为空');
        return;
      }
      
      debugPrint('📚 加载我的发布 - 用户ID: $userId');
      
      final result = await ActivityApi.getUserContent(
        userId: userId,
        days: 365,
      );
      
      // 解析进行中的活动
      final rawActivities = result['activities'] as List? ?? [];
      myOngoingActivities.value = rawActivities
          .map((item) => ActivityEntity.fromJson(item as Map<String, dynamic>))
          .toList();
      
      // 解析已结束的活动
      final rawEndedActivities = result['ended_activities'] as List? ?? [];
      myEndedActivities.value = rawEndedActivities
          .map((item) => ActivityEntity.fromJson(item as Map<String, dynamic>))
          .toList();
      
      // 解析参与的活动
      final rawParticipatedActivities = result['participated_activities'] as List? ?? [];
      myParticipatedActivities.value = rawParticipatedActivities
          .map((item) => ActivityEntity.fromJson(item as Map<String, dynamic>))
          .toList();
      
      debugPrint('✅ 我的发布加载成功');
      debugPrint('📊 进行中: ${myOngoingActivities.length}');
      debugPrint('📊 已结束: ${myEndedActivities.length}');
      debugPrint('📊 我的参与: ${myParticipatedActivities.length}');
      
    } catch (e) {
      debugPrint('❌ 我的发布加载异常: $e');
    } finally {
      isLoadingMyActivities.value = false;
    }
  }
  
  // ==================== 活动操作 ====================
  
  /// 查看活动详情
  void viewActivity(int activityId) {
    debugPrint('👁️ 查看活动详情 - ID: $activityId');
    
    // 查找活动对象（从所有列表中查找）
    ActivityEntity? activity;
    
    activity = myOngoingActivities.firstWhereOrNull((a) => a.activityId == activityId);
    if (activity == null) {
      activity = myEndedActivities.firstWhereOrNull((a) => a.activityId == activityId);
    }
    if (activity == null) {
      activity = myParticipatedActivities.firstWhereOrNull((a) => a.activityId == activityId);
    }
    
    // 跳转到活动详情页
    Get.toNamed(
      RouteNames.activityActivityDetial,
      arguments: {
        'activityId': activityId,
        'activity': activity?.toJson(), // 传递完整活动对象（如果存在）
        'fromPage': 'my_publish',
      },
    );
  }
  
  /// 编辑活动
  void editActivity(int activityId) {
    debugPrint('✏️ 编辑活动 - ID: $activityId');
    
    // 查找活动对象
    ActivityEntity? activity;
    activity = myOngoingActivities.firstWhereOrNull((a) => a.activityId == activityId);
    
    if (activity == null) {
      debugPrint('❌ 未找到活动信息');
      return;
    }
    
    // 跳转到活动编辑页
    Get.toNamed(
      RouteNames.activityActivityEdit,
      arguments: {
        'activityId': activityId,
        'title': activity.activityTitle,
        'details': activity.activityDetails ?? '',
      },
    );
  }
  
  /// 删除活动
  /// 
  /// 🔥 使用 FlutterScreenutil 适配对话框尺寸
  Future<void> deleteActivity(int activityId) async {
    final confirmed = await Get.dialog<bool>(
      AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),  // 🔥 使用.r适配
        ),
        title: Row(
          children: [
            Container(
              padding: EdgeInsets.all(8.r),  // 🔥 使用.r适配
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                ),
                borderRadius: BorderRadius.circular(10.r),  // 🔥 使用.r适配
              ),
              child: Icon(
                Icons.warning_rounded,
                color: Colors.white,
                size: 20.r,  // 🔥 使用.r适配
              ),
            ),
            SizedBox(width: 12.w),  // 🔥 使用.w适配
            Text(
              '确认删除',
              style: TextStyle(
                fontSize: 17.sp,  // 🔥 使用.sp适配
                fontWeight: FontWeight.bold,
                color: const Color(0xFF333333),
              ),
            ),
          ],
        ),
        content: Padding(
          padding: EdgeInsets.only(top: 8.h),  // 🔥 使用.h适配
          child: Text(
            '确定要删除这个活动吗？删除后无法恢复。',
            style: TextStyle(
              fontSize: 15.sp,  // 🔥 使用.sp适配
              color: const Color(0xFF666666),
              height: 1.5,
            ),
          ),
        ),
        actions: [
          // 取消按钮
          TextButton(
            onPressed: () => Get.back(result: false),
            style: TextButton.styleFrom(
              padding: EdgeInsets.symmetric(
                horizontal: 24.w,  // 🔥 使用.w适配
                vertical: 12.h,    // 🔥 使用.h适配
              ),
            ),
            child: Text(
              '取消',
              style: TextStyle(
                fontSize: 15.sp,  // 🔥 使用.sp适配
                color: const Color(0xFF999999),
              ),
            ),
          ),
          // 确认按钮（渐变）
          Container(
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
              ),
              borderRadius: BorderRadius.circular(8.r),  // 🔥 使用.r适配
            ),
            child: TextButton(
              onPressed: () => Get.back(result: true),
              style: TextButton.styleFrom(
                padding: EdgeInsets.symmetric(
                  horizontal: 24.w,  // 🔥 使用.w适配
                  vertical: 12.h,    // 🔥 使用.h适配
                ),
                foregroundColor: Colors.white,
              ),
              child: Text(
                '确定删除',
                style: TextStyle(
                  fontSize: 15.sp,  // 🔥 使用.sp适配
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
    
    if (confirmed != true) return;
    
    try {
      final userId = _userService.currentUserProfile?.userid;
      if (userId == null) {
        debugPrint('⚠️ 用户未登录，无法删除活动');
        return;
      }
      
      debugPrint('🗑️ 删除活动 - ID: $activityId');
      
      final result = await ActivityApi.deleteActivity(
        activityId: activityId,
        userId: userId,
      );
      
      if (result['status'] == 'success') {
        debugPrint('✅ 活动删除成功');
        
        // 🔥 显示成功提示（使用 LoadingUtil）
        LoadingUtil.success('活动已删除');
        
        // 刷新我的发布列表
        loadMyActivities();
      } else {
        debugPrint('❌ 活动删除失败: ${result['message']}');
        
        // 🔥 显示错误提示（使用 LoadingUtil）
        LoadingUtil.error(result['message'] ?? '删除活动失败');
      }
    } catch (e) {
      debugPrint('❌ 删除活动异常: $e');
      
      // 🔥 显示错误提示（使用 LoadingUtil）
      LoadingUtil.error('删除活动时发生错误');
    }
  }
  
  /// 管理活动（查看参与者）
  void manageActivity(int activityId) {
    debugPrint('👥 管理活动 - ID: $activityId');
    
    // 查找活动对象
    ActivityEntity? activity;
    activity = myOngoingActivities.firstWhereOrNull((a) => a.activityId == activityId);
    
    // 跳转到活动管理页
    Get.toNamed(
      RouteNames.activityActivityManage,
      arguments: {
        'activityId': activityId,
        'title': activity?.activityTitle ?? '活动管理',
      },
    );
  }
}

